package org.atlantis.grosbeak.pot.mapper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 映射工具类。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
class MapperKit {

	/**
	 * 根据Java类型获取一个字段映射。
	 * 
	 * @param jtype
	 *            Java类型。
	 * @return
	 */
	public static FieldMapper<?> getFieldMapper(Class<?> jtype) {
		return javaType.get(jtype);
	}

	/**
	 * 根据SQL类型获取一个字段映射。
	 * 
	 * @param stype
	 *            SQL类型。
	 * @return
	 */
	public static FieldMapper<?> getFieldMapper(int stype) {
		return sqlType.get(stype);
	}

	// SQL语句中的类型。
	private static Map<Integer, FieldMapper<?>> sqlType = new HashMap<Integer, FieldMapper<?>>();
	// Java中的类型。
	private static Map<Class<?>, FieldMapper<?>> javaType = new HashMap<Class<?>, FieldMapper<?>>();

	static {
		registerFieldMapper(StringFieldMapper.ME, String.class);
		registerFieldMapper(BigDecimalFieldMapper.ME, BigDecimal.class);
		registerFieldMapper(ByteArrayFieldMapper.ME, byte[].class);
		registerFieldMapper(DateFieldMapper.ME, Date.class);
		registerFieldMapper(BooleanFieldMapper.ME, boolean.class, Boolean.class);
		registerFieldMapper(DoubleFieldMapper.ME, double.class, Double.class);
		registerFieldMapper(FloatFieldMapper.ME, float.class, Float.class);
		registerFieldMapper(IntegerFieldMapper.ME, int.class, Integer.class);
		registerFieldMapper(LongFieldMapper.ME, long.class, Long.class);
		registerFieldMapper(ShortFieldMapper.ME, short.class, Short.class);
	}

	/**
	 * 把SQL中的类型和Java中的类型注册到一起。
	 * 
	 * @param fm
	 *            字段映射。
	 * @param classes
	 *            Java中的类型。
	 */
	private static void registerFieldMapper(FieldMapper<?> fm,
			Class<?>... classes) {
		int[] types = fm.getTypes();
		for (int type : types) {
			if (!sqlType.containsKey(type))
				sqlType.put(type, fm);
		}
		for (Class<?> clazz : classes) {
			javaType.put(clazz, fm);
		}
	}
}
